Telegram Group & Telegram Channel
🔧 Задача на C# для внимательных разработчиков

Что выведет следующий код?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var actions = new List<Action>();

for (int i = 0; i < 3; i++)
{
actions.Add(() => Console.WriteLine(i));
}

foreach (var action in actions)
action();
}
}


Варианты ответа:
A)

1
2


B)

3
3


C)

0
0


D)Ошибка компиляции


---

Правильный ответ: B

Почему:
Лямбда-функции захватывают переменную
i по ссылке, а не её значение на каждой итерации. После завершения цикла i == 3, и все замыкания ссылаются на одно и то же i. Это классическая ловушка замыканий в C#.

@csharp_ci



tg-me.com/csharp_ci/1329
Create:
Last Update:

🔧 Задача на C# для внимательных разработчиков

Что выведет следующий код?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var actions = new List<Action>();

for (int i = 0; i < 3; i++)
{
actions.Add(() => Console.WriteLine(i));
}

foreach (var action in actions)
action();
}
}


Варианты ответа:
A)

1
2


B)

3
3


C)

0
0


D)Ошибка компиляции


---

Правильный ответ: B

Почему:
Лямбда-функции захватывают переменную
i по ссылке, а не её значение на каждой итерации. После завершения цикла i == 3, и все замыкания ссылаются на одно и то же i. Это классическая ловушка замыканий в C#.

@csharp_ci

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1329

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

Importantly, that investor viewpoint is not new. It cycles in when conditions are right (and vice versa). It also brings the ineffective warnings of an overpriced market with it.Looking toward a good 2022 stock market, there is no apparent reason to expect these issues to change.

At a time when the Indian stock market is peaking and has rallied immensely compared to global markets, there are companies that have not performed in the last 10 years. These are definitely a minor portion of the market considering there are hundreds of stocks that have turned multibagger since 2020. What went wrong with these stocks? Reasons vary from corporate governance, sectoral weakness, company specific and so on. But the more important question is, are these stocks worth buying?

C C Sharp programming from hk


Telegram C# (C Sharp) programming
FROM USA